package com.his.his_system.controller.DruginventoryController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.his.his_system.common.util.ResultAdvice;
import com.his.his_system.common.vo.MedicinesVo;
import com.his.his_system.domain.*;
import com.his.his_system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * 药品信息
 */
@RestController
@RequestMapping("api")
public class DzmHisMedicinesController {
    @Autowired
    private DzmHisMedicinesService dzmHisMedicinesService;


    @Autowired
    private DzmHisBatchesOfInventoryService dzmHisBatchesOfInventoryService;
    @Autowired
    private DzmHisPurchaseService dzmHisPurchaseService;
    @Autowired
    private DzmHisInventoryService dzmHisInventoryService;

    @Autowired
    private DzmHisStorageLogService dzmHisStorageLogService;
    @Autowired
    private DzmHisHospitalMedicinesRelationService hmService;
    @Autowired
    private LoginInfo loginInfo;

    /**
     * 药品信息显示
     *
     * @return
     */
    @GetMapping(value = "xianshi")
    public ResultAdvice xs( DzmHisMedicines dzmHisMedicines) {










        return ResultAdvice.success(dzmHisMedicinesService.ys(dzmHisMedicines,loginInfo.getHospitalId()), "成功");
    }
    @GetMapping(value = "getMedicines")
    public ResultAdvice getMedicines( DzmHisMedicines dzmHisMedicines,Integer pageNum,Integer pageSize) {

        //1.引入分页插件,pageNum是第几页，pageSize是每页显示多少条,默认查询总数count
        Page<DzmHisBatchesOfInventory> page = PageHelper.startPage(pageNum,pageSize);
        //2.紧跟的查询就是一个分页查询-必须紧跟.后面的其他查询不会被分页
        List<DzmHisMedicines> dzmHisMedicinesList =dzmHisMedicinesService.ys(dzmHisMedicines,loginInfo.getHospitalId());
        //3.使用PageInfo包装查询后的结果,3是连续显示的条数
        PageInfo pageInfo = new PageInfo(dzmHisMedicinesList);



        return ResultAdvice.success(pageInfo, "成功");
    }

    /**
     * 调价
     *
     * @return
     */
    @GetMapping(value = "changePrice")
    public ResultAdvice changePrice(DzmHisInventory dzmHisInventory) {
        QueryWrapper<DzmHisInventory> dzmHisInventoryQueryWrapper = new QueryWrapper<>();
        dzmHisInventoryQueryWrapper.eq("hmr_id",dzmHisInventory.getHmrId());
        DzmHisInventory one = dzmHisInventoryService.getOne(dzmHisInventoryQueryWrapper);

        DzmHisStorageLog dzmHisStorageLog=new DzmHisStorageLog();
        dzmHisStorageLog.setCompanyId(one.getCompanyId());
        dzmHisStorageLog.setMedicinesId(one.getDzmHisMedicines().getMedicinesId());
        dzmHisStorageLog.setModifierId(loginInfo.getUserId());
        dzmHisStorageLog.setNewQuantity(one.getInventoryNum());
        dzmHisStorageLog.setOldQuantity(one.getInventoryNum());
        dzmHisStorageLog.setOldTradePrice(one.getInventoryTradePrice());
        dzmHisStorageLog.setNewTradePrice(one.getInventoryTradePrice());
        dzmHisStorageLog.setNewPrescriptionPrice(dzmHisInventory.getInventoryPrescriptionPrice());
        dzmHisStorageLog.setOldPrescriptionPrice(one.getInventoryPrescriptionPrice());
        dzmHisStorageLog.setCreateTime(System.currentTimeMillis());
        dzmHisStorageLog.setOperationModule(2);
        dzmHisStorageLogService.save(dzmHisStorageLog);
        dzmHisInventory.setUpdateTime(System.currentTimeMillis());
        dzmHisInventoryService.changePrice(dzmHisInventory);

        return ResultAdvice.success(null, "成功");
    }


    /**
     * 查询批次药品信息详情
     *
     * @return
     */
    @GetMapping(value = "batchDetails")
    public ResultAdvice batchDetails( DzmHisPurchase dzmHisPurchase ) {



        return ResultAdvice.success(dzmHisPurchaseService.list(dzmHisPurchase), "成功");
    }
    /**
     * 药品删除
     */

    @DeleteMapping(value = "DzmHisMedicinesshanchu")
    public ResultAdvice shanchu(Integer hmrId){
        QueryWrapper<DzmHisInventory> dzmHisInventoryQueryWrapper = new QueryWrapper<>();
        dzmHisInventoryQueryWrapper.eq("hmr_id",hmrId);
        DzmHisInventory dzmHisInventory = dzmHisInventoryService.getOne(dzmHisInventoryQueryWrapper);
        System.out.println(dzmHisInventory==null);
        if(dzmHisInventory==null){
             hmService.removeById(hmrId);
           return ResultAdvice.success(true, "删除成功");
        }
        return ResultAdvice.success(false, "医院已有该药品进货记录，不可删除");
    }

    /**
     * 批次查询
     */

    @GetMapping(value = "getbatchesOfInventory")
    public ResultAdvice getbatchesOfInventory(DzmHisBatchesOfInventory dzmHisBatchesOfInventory,Integer pageNum,Integer pageSize,String beginBatchesOfInventoryDate,String endBatchesOfInventoryDate){
        PageHelper pageHelper = new PageHelper();

        //1.引入分页插件,pageNum是第几页，pageSize是每页显示多少条,默认查询总数count
        Page<DzmHisBatchesOfInventory> page = PageHelper.startPage(pageNum,pageSize);
        //2.紧跟的查询就是一个分页查询-必须紧跟.后面的其他查询不会被分页
        dzmHisBatchesOfInventory.setCompanyId(loginInfo.getHospitalId());
        List<DzmHisBatchesOfInventory> dzmHisBatchesOfInventoryList = dzmHisBatchesOfInventoryService.selectDzmHisBatchesOfInventoryList(dzmHisBatchesOfInventory,beginBatchesOfInventoryDate,endBatchesOfInventoryDate);
        //3.使用PageInfo包装查询后的结果,3是连续显示的条数
        PageInfo pageInfo = new PageInfo(dzmHisBatchesOfInventoryList);


        return ResultAdvice.success(pageInfo, "成功");
    }/*
    库存查询

    */

    @GetMapping(value = "getInventorys")
    public ResultAdvice getInventorys(DzmHisMedicines dzmHisMedicines
            ,Integer pageNum,Integer pageSize){
        PageHelper pageHelper = new PageHelper();

        //1.引入分页插件,pageNum是第几页，pageSize是每页显示多少条,默认查询总数count
        Page<DzmHisBatchesOfInventory> page = PageHelper.startPage(pageNum,pageSize);
        //2.紧跟的查询就是一个分页查询-必须紧跟.后面的其他查询不会被分页
        List<DzmHisInventory> dzmHisInventoryList = dzmHisInventoryService.selectDzmHisInventoryList(dzmHisMedicines,loginInfo.getHospitalId());
        //3.使用PageInfo包装查询后的结果,3是连续显示的条数
        PageInfo pageInfo = new PageInfo(dzmHisInventoryList);


        return ResultAdvice.success(pageInfo, "成功");
    }



    /**
     * 采购页面入库
     *
     * @return
     */
    @PostMapping (value = "insertMedicines")
    public ResultAdvice<Object> insertMedicines ( @RequestBody MedicinesVo mv ) {






        DzmHisBatchesOfInventory dzmHisBatchesOfInventory = new DzmHisBatchesOfInventory();
        dzmHisBatchesOfInventory.setBatchesOfInventoryId(null);
        dzmHisBatchesOfInventory.setCompanyId(loginInfo.getHospitalId());
        dzmHisBatchesOfInventory.setSupplierId(mv.getSupplierId());
        dzmHisBatchesOfInventory.setBatchesOfInventoryNumber(mv.getBatchesOfInventoryNumber());
        dzmHisBatchesOfInventory.setPurchasingAgentId(String.valueOf(loginInfo.getUserId()));
        dzmHisBatchesOfInventory.setBatchesOfInventoryTotalMoney(BigDecimal.valueOf(mv.getPurchaseTradePriceTotle()));

        dzmHisBatchesOfInventory.setBatchesOfInventoryDate(System.currentTimeMillis());
        dzmHisBatchesOfInventory.setBatchesOfInventoryStatus(mv.getStatus());
        if (mv.getStatus()==1){
            dzmHisBatchesOfInventory.setBatchesOfInventoryVerifier(null);
            dzmHisBatchesOfInventory.setBatchesOfInventoryVerifierDate(null);
        }else {
            dzmHisBatchesOfInventory.setBatchesOfInventoryVerifier(String.valueOf(loginInfo.getUserId()));
            dzmHisBatchesOfInventory.setBatchesOfInventoryVerifierDate(System.currentTimeMillis());
        }


        dzmHisBatchesOfInventory.setCreateTime(System.currentTimeMillis());
//      dzmHisBatchesOfInventory.setUpdateTime(null);
        //批次插入
       dzmHisBatchesOfInventoryService.save(dzmHisBatchesOfInventory);

            // 获取批次id
            Integer primaryKey =  dzmHisBatchesOfInventory.getBatchesOfInventoryId();
        System.out.println(primaryKey);

            //插入药品采购信息
        for (DzmHisPurchase datum : mv.getData()) {
            datum.setMedicinesName(null);
            datum.setBatchesOfInventoryId(primaryKey);

            BigDecimal PurchaseNum = new BigDecimal(datum.getPurchaseNum());
            datum.setPurchaseTradeTotalAmount(datum.getPurchaseTradePrice().multiply(PurchaseNum));
            datum.setPurchasePrescriptionTotalAmount(datum.getPurchasePrescriptionPrice().multiply(PurchaseNum));

            datum.setCreateTime(System.currentTimeMillis());



        }
        dzmHisPurchaseService.saveBatch(mv.getData());



        //判断审核状态决定是否直接入库 1，审核入库 2.直接入库
        if(mv.getStatus()==2){
            warehousing(mv.getData());
//            DzmHisStorageLog dzmHisStorageLog=new DzmHisStorageLog();
//            dzmHisStorageLog.setCompanyId(loginInfo.getHospitalId());
//            dzmHisStorageLog.s


        }





        return ResultAdvice.success(null, "成功");

    }
            /*
            * 审核入库和再次入库
            * */
        @GetMapping(value = "auditAndWarehousing")
        public ResultAdvice auditAndWarehousing(DzmHisPurchase dzmHisPurchase,Integer type){



            List<DzmHisPurchase>  dzmHisPurchaseList=dzmHisPurchaseService.list(dzmHisPurchase);

            //判断是否点击的再次入库
         if (type==2){
             DzmHisBatchesOfInventory dzmHisBatchesOfInventory=dzmHisBatchesOfInventoryService.getById(dzmHisPurchase.getBatchesOfInventoryId());

             dzmHisBatchesOfInventory.setBatchesOfInventoryId(null);
             dzmHisBatchesOfInventory.setBatchesOfInventoryDate(System.currentTimeMillis());
             dzmHisBatchesOfInventory.setPurchasingAgentId(String.valueOf(loginInfo.getUserId()));
             dzmHisBatchesOfInventory.setCreateTime(System.currentTimeMillis());
             dzmHisBatchesOfInventory.setBatchesOfInventoryVerifier(String.valueOf(loginInfo.getUserId()));
             dzmHisBatchesOfInventory.setBatchesOfInventoryVerifierDate(System.currentTimeMillis());

             dzmHisBatchesOfInventory.setBatchesOfInventoryNumber(System.currentTimeMillis());
             //再次插入批次
             dzmHisBatchesOfInventoryService.save(dzmHisBatchesOfInventory);


             // 获取批次id
             Integer primaryKey =  dzmHisBatchesOfInventory.getBatchesOfInventoryId();




             for (DzmHisPurchase datum : dzmHisPurchaseList) {
                 datum.setMedicinesName(null);
                 datum.setBatchesOfInventoryId(primaryKey);



             }
             //再次插入采购信息
             dzmHisPurchaseService.saveBatch(dzmHisPurchaseList);
         }else{



                 UpdateWrapper<DzmHisBatchesOfInventory> updateWrapper = new UpdateWrapper<DzmHisBatchesOfInventory>();

                 updateWrapper.set("batches_of_inventory_status",2);
                 updateWrapper.set("batches_of_inventory_verifier",loginInfo.getUserId());
                 updateWrapper.set("batches_of_inventory_verifier_date",System.currentTimeMillis());


                 updateWrapper.eq("batches_of_inventory_id", dzmHisPurchase.getBatchesOfInventoryId());


                //修改批次审核状态
                 dzmHisBatchesOfInventoryService.update(updateWrapper);







         }


        warehousing(dzmHisPurchaseList);

        return ResultAdvice.success( null, "成功");
    }

    /*
     *添加日志方法
     */
    private DzmHisInventory addLog(DzmHisPurchase data ){

        DzmHisStorageLog dzmHisStorageLog=new DzmHisStorageLog();
        dzmHisStorageLog.setCompanyId(loginInfo.getHospitalId());


        dzmHisStorageLog.setPurchaseId(data.getPurchaseId());


        DzmHisBatchesOfInventory dzmHisBatchesOfInventory=dzmHisBatchesOfInventoryService.getById(data.getBatchesOfInventoryId());
        dzmHisStorageLog.setBatchesOfInventoryNumber(dzmHisBatchesOfInventory.getBatchesOfInventoryNumber());
        dzmHisStorageLog.setMedicinesId(data.getMedicinesId());
        dzmHisStorageLog.setModifierId(Integer.valueOf(dzmHisBatchesOfInventory.getBatchesOfInventoryVerifier()));
        dzmHisStorageLog.setNewTradePrice(data.getPurchaseTradePrice());
        dzmHisStorageLog.setNewPrescriptionPrice(data.getPurchasePrescriptionPrice());
        QueryWrapper<DzmHisInventory> dzmHisInventoryQueryWrapper = new QueryWrapper<>();
        dzmHisInventoryQueryWrapper.eq("hmr_id",data.getHmrId());
        DzmHisInventory dzmHisInventory = dzmHisInventoryService.getOne(dzmHisInventoryQueryWrapper);


        if(dzmHisInventory==null){
            dzmHisStorageLog.setOldTradePrice(BigDecimal.valueOf(0));
            dzmHisStorageLog.setOldPrescriptionPrice(BigDecimal.valueOf(0));
            dzmHisStorageLog.setOldQuantity(0);
            dzmHisStorageLog.setNewQuantity(data.getPurchaseNum());
        }else {
            dzmHisStorageLog.setOldTradePrice(dzmHisInventory.getInventoryTradePrice());
            dzmHisStorageLog.setOldPrescriptionPrice(dzmHisInventory.getInventoryPrescriptionPrice());
            dzmHisStorageLog.setOldQuantity(Math.toIntExact(dzmHisInventory.getInventoryNum()));
            dzmHisStorageLog.setNewQuantity(Math.toIntExact(dzmHisInventory.getInventoryNum())+data.getPurchaseNum());
        };

        dzmHisStorageLog.setOperationModule(1);
        dzmHisStorageLog.setCreateTime(System.currentTimeMillis());
        dzmHisStorageLogService.save(dzmHisStorageLog);
        return dzmHisInventory;

    }
    /*
    *入库方法
     */
    private void warehousing(List<DzmHisPurchase> data){

        for (DzmHisPurchase datum : data) {

            BigDecimal PurchaseNum = new BigDecimal(datum.getPurchaseNum());
            //判断库存表是否已经有该药品信息，如果有只改信息没有则插入
            if ( addLog(datum)==null) {

                System.out.println(">>>>>>>>>");
                DzmHisInventory dzmHisInventory = new DzmHisInventory();
                dzmHisInventory.setHmrId(datum.getHmrId());
                dzmHisInventory.setInventoryUnit(datum.getPurchaseUnit());
                dzmHisInventory.setCompanyId(loginInfo.getHospitalId());
                dzmHisInventory.setInventoryNum(datum.getPurchaseNum());
                dzmHisInventory.setInventoryTradePrice(datum.getPurchaseTradePrice());
                dzmHisInventory.setInventoryPrescriptionPrice(datum.getPurchasePrescriptionPrice());
                dzmHisInventory.setInventoryTradeTotalAmount(datum.getPurchaseTradePrice().multiply(PurchaseNum));
                dzmHisInventory.setInventoryPrescriptionTotalAmount(datum.getPurchasePrescriptionPrice().multiply(PurchaseNum));
                dzmHisInventory.setEarlyWarning("20");
                dzmHisInventory.setUpdateTime(System.currentTimeMillis());
                dzmHisInventoryService.save(dzmHisInventory);

            } else {

                DzmHisInventory dzmHisInventory = new DzmHisInventory();
                dzmHisInventory.setHmrId(datum.getHmrId());

                dzmHisInventory.setInventoryNum(datum.getPurchaseNum());
                dzmHisInventory.setInventoryTradePrice(datum.getPurchaseTradePrice());
                dzmHisInventory.setInventoryPrescriptionPrice(datum.getPurchasePrescriptionPrice());
                //算出此次批发额和处方额通过dzmHisInventory传给xml
                dzmHisInventory.setInventoryTradeTotalAmount(datum.getPurchasePrescriptionPrice().multiply(PurchaseNum));
             dzmHisInventory.setUpdateTime(System.currentTimeMillis());
                dzmHisInventoryService.update(dzmHisInventory);
                dzmHisInventoryService.changePrice(dzmHisInventory);


            }

        }

    }

    @GetMapping("medical_info")
    public ResultAdvice getInfo() {

        List<DzmHisMedicines> medicines = dzmHisMedicinesService.getMedicalInfo();
        return ResultAdvice.success(medicines);
    }

    @PostMapping("modify_h_med")
    public ResultAdvice updataHM(@RequestBody ArrayList<Integer> ids) {

        return ResultAdvice.success(hmService.saves(ids));
    }    /**
     * 查询导入药品信息
     */
    @GetMapping(value = "DzmHisMedicinesdaoruchaxun")
    public List<DzmHisMedicines>chaxun2(String medicinesName){
        QueryWrapper<DzmHisMedicines>qu=new QueryWrapper<>();
        qu.like("medicines_name",medicinesName);
        return  dzmHisMedicinesService.list(qu);
    }






}
